from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
from .models import (
    UserProfile, PhoneNumber, Plan, PhonePlan, 
    Balance, Payment, UsageRecord
)


class UserProfileInline(admin.StackedInline):
    model = UserProfile
    can_delete = False
    verbose_name_plural = '用户资料'


class UserAdmin(UserAdmin):
    inlines = (UserProfileInline,)


class PhoneNumberInline(admin.TabularInline):
    model = PhoneNumber
    extra = 0
    fields = ('number', 'is_primary', 'created_at')


@admin.register(UserProfile)
class UserProfileAdmin(admin.ModelAdmin):
    list_display = ('user', 'created_at', 'updated_at')
    list_filter = ('created_at', 'updated_at')
    search_fields = ('user__username', 'user__email')


@admin.register(PhoneNumber)
class PhoneNumberAdmin(admin.ModelAdmin):
    list_display = ('number', 'user', 'is_primary', 'created_at')
    list_filter = ('is_primary', 'created_at')
    search_fields = ('number', 'user__username')
    list_editable = ('is_primary',)


@admin.register(Plan)
class PlanAdmin(admin.ModelAdmin):
    list_display = ('name', 'monthly_fee', 'data_allowance', 'voice_allowance', 'is_active')
    list_filter = ('is_active', 'monthly_fee')
    search_fields = ('name', 'description')
    list_editable = ('is_active',)


@admin.register(PhonePlan)
class PhonePlanAdmin(admin.ModelAdmin):
    list_display = ('phone_number', 'plan', 'start_date', 'is_active')
    list_filter = ('is_active', 'plan', 'start_date')
    search_fields = ('phone_number__number', 'plan__name')


@admin.register(Balance)
class BalanceAdmin(admin.ModelAdmin):
    list_display = ('phone_number', 'amount', 'data_remaining', 'voice_remaining', 'last_updated')
    list_filter = ('last_updated',)
    search_fields = ('phone_number__number',)
    readonly_fields = ('last_updated',)


@admin.register(Payment)
class PaymentAdmin(admin.ModelAdmin):
    list_display = ('phone_number', 'amount', 'payment_method', 'payment_time')
    list_filter = ('payment_method', 'payment_time')
    search_fields = ('phone_number__number', 'description')
    readonly_fields = ('payment_time',)


@admin.register(UsageRecord)
class UsageRecordAdmin(admin.ModelAdmin):
    list_display = ('phone_number', 'usage_type', 'amount_used', 'usage_time')
    list_filter = ('usage_type', 'usage_time')
    search_fields = ('phone_number__number', 'description')
    readonly_fields = ('usage_time',)


# 重新注册User模型
admin.site.unregister(User)
admin.site.register(User, UserAdmin)